package com.lin.csdn.controller;

import com.lin.csdn.service.impl.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/MasterServlet")
public class MasterServlet extends HttpServlet {
    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     *
     * 0：根据页数获取用户的信息 GetUserInformation
     * 1：封禁用户 BanUser
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //建立功能代表的code调用
        String GetUserInformation="0";
        String BanUser ="1";
        //获取req数据
        String code=req.getParameter("code");

        List<Object> data;
        UserService userService=new UserService();
        PrintWriter writer = resp.getWriter(); //响应流

        //根据需求调用各自的方法
        if(code.equals(GetUserInformation)){
            String Page=req.getParameter("currentPage");
            int currentPage=Integer.parseInt(Page);
            //设置每次查询的条数
            int pageSize=10;
            int beginIndex = (currentPage - 1) * pageSize;
            data=userService.searchAll(beginIndex,pageSize);
            JSONArray array = new JSONArray();
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = new JSONObject();
                object.put("id", data.get(i));
                i++;
                object.put("name", data.get(i));
                i++;
                object.put("email", data.get(i));
                i++;
                object.put("identity", data.get(i));
                i++;
                object.put("status", data.get(i));
                array.put(object);
            }
            writer.print(array);
        }
        else if(code.equals(BanUser)){
            JSONObject object = new JSONObject();
            String userId=req.getParameter("userId");
            userService.banUser(userId);
            object.put("code","200");
            writer.print(object);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
